package com.zl.test.restdemo.service.impl;

import com.alibaba.fastjson.JSON;
import com.zl.test.restdemo.common.constant.DomeConstant;
import com.zl.test.restdemo.entity.MiddleStudent;
import com.zl.test.restdemo.entity.MiddleStudentExample;
import com.zl.test.restdemo.mapper.MiddleStudentMapper;
import com.zl.test.restdemo.service.MiddleStudentService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zhang lei
 * @Describe: All things are difficult before they are easy.
 * @CreatTime: 2021-02-24-16-43
 */
@Service
public class MiddleStudentServiceImpl implements MiddleStudentService {
    @Autowired
    private MiddleStudentMapper studentMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public MiddleStudent quertStuByName(String name) {
        MiddleStudentExample example = new MiddleStudentExample();
        example.createCriteria().andNameEqualTo(name);
        List<MiddleStudent> middleStudents = studentMapper.selectByExample(example);
        return middleStudents.get(0);
    }

    @Override
    public List<MiddleStudent> selectAll() {
        String  s = (String) redisTemplate.opsForValue().get(DomeConstant.REDIS_STUDENT_KEY);
        if (StringUtils.isBlank(s)) {
            List<MiddleStudent> list = studentMapper.selectAll();
            if (CollectionUtils.isEmpty(list)) {
                return new ArrayList<>();
            }
            redisTemplate.opsForValue().set(DomeConstant.REDIS_STUDENT_KEY,list.toString(),50000, TimeUnit.SECONDS);
            return list;
        }
        return JSON.parseArray(s,MiddleStudent.class);
    }
}
